﻿using System.Collections.Generic;
using DO.DreamOnTrader.Indicator;

namespace DO.DreamOnTrader.Indicator
{
	/// <summary>
	/// 可以保留前幾個計算值的class
	/// </summary>
	public class QueueIndicator : IIndicator, IActiveIndicator
	{
		public QueueIndicator(IActiveIndicator _indicator, int _lastNValue)
		{
			indicator = _indicator;
			LastNValue = _lastNValue;
			indicator.GetValueEvent += new getValueEventHandler(addValue);
		}

		IActiveIndicator indicator;

		/// <summary>
		/// 取倒數幾根的值，0為最新一個，1為前一個...類推
		/// </summary>
		public int LastNValue { get; protected set; }

		/// <summary>
		/// 真正儲存指標的值
		/// </summary>
		private Queue<float> ValueQueue = new Queue<float>();

		private void addValue(float value, IIndicator indicator)
		{
			if (!float.IsNaN(value))
				Value = value;

			if (GetValueEvent != null)
				GetValueEvent(Value, this);
		}

		/// <summary>
		/// 子類別計算出來的值擺在這
		/// </summary>
		private float Value
		{
			set
			{
				lock (ValueQueue)
				{
					while (ValueQueue.Count > LastNValue) ValueQueue.Dequeue();
					ValueQueue.Enqueue(value);
				}
			}
			get
			{
				lock (ValueQueue)
				{
					if (ValueQueue.Count > LastNValue)
						return ValueQueue.Peek();
					else
						return float.NaN;
				}
			}
		}

		

		#region Indicator 成員

		public float getValue(DO.DreamOnTrader.Quote.Tick tick)
		{
			indicator.getValue(tick);
			return Value;
		}

		public float getValue(DO.DreamOnTrader.Quote.KBar kbar)
		{
			indicator.getValue(kbar);
			return Value;
		}

		public float getValue()
		{
			return Value;
		}
		
		public string Label()
		{
			return "Last " + LastNValue + " (" + indicator.Label() + ")";
		}

		public override string ToString()
		{
			return Label() + ":" + Value;
		}

		#endregion

		#region IActiveIndicator 成員

		public event getValueEventHandler GetValueEvent;

		#endregion
	}
}
